package com.web.base.log.provider;

import com.blue.core.dict.Result;
import com.blue.integration.serve.SmsClient;
import com.blue.jdbc.Page;
import com.blue.validation.spi.MobileValidator;
import com.web.base.log.exception.SmsException;
import com.web.base.log.facade.SmsFacade;
import com.web.base.log.message.SmsRequest;
import com.web.base.log.message.SmsResponse;
import com.web.base.log.model.Sms;
import com.web.base.log.service.SmsService;
import com.web.base.log.util.SmsConvertor;
import com.web.base.user.service.UserService;
import com.web.core.dict.SmsType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ValidationException;
import java.util.Date;

/**
 * 短信日志接口实现类
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年11月21日
 */
@Component("logSmsProvider")
public class SmsProvider implements SmsFacade
{
	private static Logger logger = LoggerFactory.getLogger(SmsProvider.class);

	@Autowired
	private SmsService smsService;
	@Autowired
	private UserService userService;
	@Autowired(required = false)
	private SmsClient smsClient;
	
	public SmsProvider()
	{
	}

	@Override
	public Page<SmsResponse> listPage(SmsRequest request, int start, int size)
	{
		Sms sms = SmsConvertor.toSms(request);
		Page<Sms> page = new Page<>(size);
		page.setCurPage(start);
		page = smsService.list(sms, page);
		Page<SmsResponse> pageResponse = SmsConvertor.toResponse(page);
		return pageResponse;
	}

	@Override
	public void sendMobileValid(String mobile, String num)
	{
		if (mobile == null || mobile.isEmpty() || !MobileValidator.isValid(mobile))
			throw new ValidationException("手机号码格式错误");

		if (userService.isMobileExist(mobile))
			throw new SmsException("手机号码已经存在");

		Result result = Result.SUCCESS;
		String seq = null;
		try
		{
			seq = smsClient.sendValid(mobile, num);
		}
		catch (Exception e)
		{
			result = Result.FAIL;
			logger.error("发送短信失败", e);
		}

		Sms sms = new Sms();
		sms.setMobile(mobile);
		sms.setType(SmsType.VALID);
		sms.setParams(num);
		sms.setResult(result);
		sms.setSendTime(new Date());
		sms.setSeq(seq);
		smsService.save(sms);

	}

}
